# -*- coding:utf-8 -*-
from urllib import request, parse
import json
#
class zabbix_tg(object):
    def __init__(self):
        self.url = ""
        self.username = ""
        self.password = ""
        self.values = {
            "jsonrpc": "2.0",
            "id": "0"
        }
        self.token = ""

    def request_data(self, values):
        data = json.dumps(values)
        req = request.Request(self.url, data, {"Content-Type": "application/json-rpc"})
        bdata = bytes(data, encoding="utf8")
        response = request.urlopen(req, bdata)
        output = json.loads(response.read())
        return output

    # def auth_user(self):
    #     self.values["method"] = "user.login"
    #     self.values["params"] = {
    #         "user": self.username,
    #         "password": self.password
    #     }
    #     token = self.requestJson(self.values)
    #     print(token)
    #     return token
    #
    # def requestJson(self,values):
    #     output = self.request_data(values)
    #     try:
    #         message = output["result"]
    #     except:
    #         message = output["error"]["data"]
    #         print("error")
    #     finally:
    #         return message

    def host_ID(self):
        zid = {}
        zip = {}
        self.values["method"] = "host.get"
        self.values["params"] = {
            "output": [
                "hostid",
                "host"
            ],
            "selectInterfaces": [
                "interfaceid",
                "ip"
            ]
        }
        self.values["auth"] = self.token
        output = self.request_data(self.values)
        # print(output)
        out_result = output["result"]
        for i in out_result:
            zid[i["host"]] = i["hostid"]
            zip[i["host"]] = i["interfaces"][0]["ip"]
        return zid, zip

    def trigger_data(self):
        # auth_user()
        zid, zip = self.host_ID()
        triggerl = []
        for k, v in zid.items():
            triggers = {}
            self.values["method"] = "trigger.get"
            self.values["params"] = {
                "hostids": v,
                "only_true": 0,
                "min_severity": 3,
                "monitored": 0,
                "output": [
                    "triggerid",
                    "description",
                    "priority"
                ],
                "filter": {
                    "value":1
                },
                # "output" : "extend",
                "sortfield": "priority",
                "sortorder": "DESC"
            }
            output = self.request_data(self.values)
            results = output["result"]
            if len(results) != 0:
                triggers["servername"] = k
                triggers["ip"] = zip[k]
                triggers["error"] = results
                triggerl.append(triggers)
        print(triggerl)
        return triggerl

if __name__ == "__main__":
    a = zabbix_tg()
    a.trigger_data()